﻿package com.cilico.components;

import java.util.Vector;
import com.cilico.ConfigManager;
import com.cilico.Mid;
import com.cilico.utils.HttpManager.EmptyResultException;
import com.cilico.utils.Utils;
import com.cilico.view.BaseView;
import com.cilico.view.Channel;

/**
 * 保存channel列表
 * 
 * @author lv.xiangan
 *
 */
public final class ChannelRepository {
	public final Mid mid_;
	public final Collection defaultCollection_; //默认collection，保存的是从服务器下载所有的channels
	public Collection currentCollection_; // 当前活动的collection
	private final Vector<Channel> channels_; // 保存当前collection中所有的channels
	private final Paging paging_; // 控制channel列表分页
	private boolean initDownloadRequired_;// true时，在显示collection前必须从服务器下载channel
	int appendedPredefChannelIdx_; // Indicate a predefined channel appended
	protected int selectedIndex_; // 上一个选择item的index
	private String currentChannelID_; // 在ChannelRepository中，focused/selected/shown的channel对应的ID。
	private final int CHANNEL_NUM_PER_PAGE = 100;

	public ChannelRepository(Mid mid) {
		mid_ = mid;
		channels_ = new Vector<Channel>();
		currentCollection_ = null;
		paging_ = new Paging();
		defaultCollection_ = new Collection("Default");
		// 除非我们能够从RMS获取，否则我们必须从服务器获取channels
		initDownloadRequired_ = true;
	}

	/**
	 * 根据channel ID 下载对应页面
	 * Download channel listing from server. This is public so that we have a menu to explicitly update channel listing
	 * information. This also populates the collection listing since they come together.
	 */
	public void downloadChannelList(WaitDialog.Task task, String id) throws Exception {
		reset();
		// We only download this user's channel; we cannot get all public channels.
		StringBuffer url = new StringBuffer(ConfigManager.SERVER_URI);
		url.append(ConfigManager.COLLECTION_LIST_URI);
		url.append("channel!");//接口名字
		if (id != null) {
			url.append(id+".html");//新定义的请求模式
			url.append("?s=" + CHANNEL_NUM_PER_PAGE); // NOTE: we are downloading a long list of channels.
		}
		url.append("&p=");
		url.append(paging_.downloadPage_);
		if (null == mid_.parser_)
			mid_.parser_ = new AtomParser(BaseView.mid_);
		mid_.parser_.setChannelListingProperty(AtomParser.parseChannelListing_, this, id);
		String reply = new String(mid_.hm_.sendRequest(url.toString(), task).getBytes("UTF-8"));
		// 模拟二级菜单报文
//		String reply = Utils.getStringFormAsset(ConfigManager.currentView_, "xmlview/secondmenu2.xml");
		android.util.Xml.parse(reply, mid_.parser_);
		if (!(channels_.size() > 0)) {
			// 无法从服务器下载channels.尽管无法下载，但我们必须创建预定义的channels
			reset();
			if (id == null) {
				initDownloadRequired_ = true;
			}
			throw new EmptyResultException("无法取得相关内容.");
		} else {
			// The default collection contains every downloaded channel.
			downloadChannelListSuccess();
		}
	}

	/**
	 * Failed to load channels.
	 */
	@SuppressWarnings("serial")
	public static final class ChannelErrorException extends Exception {
		public ChannelErrorException(String str) {
			super(str);
		}
	}

	public Paging getPaging() {
		return paging_;
	}

	/**
	 * Callback from AtomParser to add a new workspace. NOTE: after a collection is allocated, its index must never
	 * change.
	 * 
	 * NOTE: We store channels of all workspaces in the same collection. The idea is to reduce the level of references
	 * the user goes through to find a channel.
	 */
	Collection addWorkspace(String workspaceTitle) {
		return defaultCollection_;
	}

	public int getSize() {
		return channels_.size();
	}

	/**
	 * Add a new channel to the list. We sort channels in ascending order of the channel name.
	 */
	public void addChannel(Channel channel) {
		channels_.addElement(channel);
	}

	public String[] getChannelTitles() {
		String[] titles = null;
		String[] icons = null;
		if (channels_ == null || channels_.size() < 1) {
			return titles;
		}
		titles = new String[channels_.size()];
		icons = new String[channels_.size()];
		for (int i = 0; i < titles.length; i++) {
			titles[i] = ((Channel) channels_.elementAt(i)).title();
			icons[i] = ((Channel) channels_.elementAt(i)).getIconName_();
		}
		return titles;
	}
	/**
	 * 获取所有二级菜单里的图片
	 * @return
	 */
	public String[] getIconNames(){
		String[] icons = null;
		if (channels_ == null || channels_.size() < 1) {
			return icons;
		}
		icons = new String[channels_.size()];
		for (int i = 0; i < icons.length; i++) {
			icons[i] = ((Channel) channels_.elementAt(i)).getIconName_();
		}
		return icons;
	}
	
	public Channel getCurrentChannel() {
		return getChannel(getCurrentChannelID());
	}

	public String getCurrentChannelID() {
		return currentChannelID_;
	}

	public Channel getChannel(String id) {
		int sz = 0;
		if (channels_ != null)
			sz = channels_.size();
		for (int i = 0; i < sz; ++i) {
			Channel ch = (Channel) channels_.elementAt(i);
			if (ch != null && ch.id().equals(id))
				return ch;
		}
		return null;
	}
	
	String getCurrentChannelTitle() {
		String title = null;
		Channel ch = null;
		ch = getCurrentChannel();
		if (ch != null) {
			title = ch.title();
		}
		return title;
	}

	public void downloadChannelListSuccess() {
		// The default collection contains every downloaded channel.
		indexChannels();
		currentCollection_ = defaultCollection_;
		currentCollection_.setChannelIndexRange(0, channels_.size());
		initDownloadRequired_ = false;
	}

	/**
	 * NOTE: At this point the index of channels is the same as the indices in the collection table.
	 */
	public void indexChannels() {
		Channel p;
		for (int i = 0; i < channels_.size(); ++i) {
			p = (Channel) channels_.elementAt(i);
			p.setIndex(i);
		}
	}

	public int setCurrentChannel(Channel currentChannel) {
		if (currentChannel == null) {
			return 0;
		}
		int idx = currentChannel.index();
		ChannelRepository r = mid_.channelRepo_;
		Channel ch = r.getChannel(currentChannel.id());
		if (ch == null) {
			// this happen when delete a channel from your phone via the web
			// site and then update your channel list.
			if (idx < r.currentCollection_.start_)
				idx = r.currentCollection_.start_;
			if (idx >= r.currentCollection_.end_)
				idx = r.currentCollection_.end_ - 1;
			ch = r.getChannel(idx);
			mid_.poiRepo_.channel_ = ch;
			mid_.poiRepo_.poiXML_ = null;
		} else {
			idx = ch.index();
			ch.userName_ = currentChannel.userName_;
			ch.passWord_ = currentChannel.passWord_;
		}
		mid_.channelRepo_.selectedIndex_ = idx;
		return idx - r.currentCollection_.start_;
	}

	public Channel getChannel(int idx) {
		if (channels_ == null)
			return null;
		return (idx < 0 || idx >= channels_.size()) ? null : (Channel) channels_.elementAt(idx);
	}

	public Channel getChannelByShortCut(String sCut) {
		for (int i = 0; i < channels_.size(); ++i) {
			Channel ch = (Channel) channels_.elementAt(i);
			if (ch.shortCut_ != null && ch.shortCut_.toLowerCase().equals(sCut.toLowerCase()))
				return ch;
		}
		return null;
	}
	

	public void setCurrentChannelID(String currentChannelID) {
		currentChannelID_ = currentChannelID;
	}

	public void setCurrentChannelID(int index) {
		Channel ch = getChannel(index);
		if (ch != null) {
			currentChannelID_ = ch.id();
		}
	}

	int getCurrentChannelIndex() {
		int index = -1;
		Channel ch = null;
		ch = getCurrentChannel();
		if (ch != null) {
			index = ch.index();
		}
		return index;
	}

	public void reset() {
		currentCollection_ = null;
		removeChannels();
		initDownloadRequired_ = true;
		// paging_.reset();
		selectedIndex_ = -1;
	}

	void removeChannels() {
		if (channels_ != null) {
			channels_.removeAllElements();
		}
	}

	public boolean isInitDownloadRequired() {
		return initDownloadRequired_;
	}
}
